/*
 * @Author: sunkai@xinxinapp.cn
 * @Date: 2020-12-15 16:55:17
 * @LastEditTime: 2020-12-15 18:36:24
 * @LastEditors: sunkai@xinxinapp.cn
 * @Description: gulp入口文件
 * @FilePath: /fed-e-task-02-01/gulpfile.js
 */

// 实现这个项目的构建任务

const del = require('del')

const { src, dest, parallel, series, watch } = require('gulp')

const plugins = require('gulp-load-plugins')()
const bs = require('browser-sync').create()

// 清除上次打包任务结果
const clean = () => { 
  return del(['dist', 'temp'])
}

const data = {}

// JS处理
const scripts = () => {
  // base 参数输入出目录和输入保持一致
  return src('src/assets/scripts/*.js', { base: 'src' })
    .pipe(plugins.babel({ presets: ['@babel/preset-env'] }))
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}

// 样式处理
const styles = () => {
  return src('src/assets/styles/*.scss', { base: 'src' })
    .pipe(plugins.sass({ outputStyle: 'expanded' }))
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}

// html处理
const html = () => {
  return src('src/*.html', { base: 'src' })
    .pipe(plugins.swig({ data, defaults: { cache: false } }))
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}
 
// 图片处理
const images = () => {
  return src('src/assets/images/**', { base: 'src' })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

// 字体文件
const fonts = () => {
  return src('src/assets/fonts/**', { base: 'src' })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

// 剩余资源
const extra = () => {
  return src('public/**', { base: 'public' })
    .pipe(dest('dist'))
}

// hot reload
const serve = () => {
  watch('src/assets/styles/*.scss', styles)
  watch('src/assets/scripts/*.js', scripts)
  watch('src/*.html', html)
  watch([
    'src/assets/images/**',
    'src/assets/fonts/**',
    'public/**'
  ], bs.reload)

  bs.init({
    notify: false,
    // port: 3000,
    server: {
      baseDir: ['temp', 'src', 'public'],
      routes: {
        '/node_modules': 'node_modules'
      }
    }
  })
}

const useref = () => {
  return src('temp/*.html', { base: 'temp' })
    .pipe(plugins.useref({ searchPath: ['temp', '.'] }))
    .pipe(plugins.if(/\.js$/, plugins.uglify()))
    .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
    .pipe(plugins.if(/\.html$/, plugins.htmlmin({
      collapseWhitespace: true,
      minifyCSS: true,
      minifyJS: true
    })))
    .pipe(dest('dist'))
}

// 编译
const compile = parallel(html, scripts, styles)

// 开发调试
const dev = series(compile, serve)

// 上线发布
const build = series(
  clean, parallel(
    series(compile, useref),
    images,
    fonts,
    extra
  )
)

module.exports = {
  clean,
  build,
  dev,
}